package com.rimuru.datastructure.binarytree.mybinarytree;

import com.rimuru.datastructure.binarytree.TreeNode;
import com.rimuru.datastructure.stack.LinkedListStack;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树前序遍历(值,左,右)
 */
public class E01Leetcode144 {


    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode currt = root;
        TreeNode pop = null;
        while (currt != null || !stack.isEmpty()) {
            if(currt !=null) {
                stack.push(currt);
                // 值先处理
                result.add(currt.val);
                // 向左遍历
                currt = currt.left;
            }else {
                TreeNode peek = stack.peek();
                // 没有右子树
                if (peek.right == null) {
                    pop = stack.pop();
                }
                // 右边处理完成
                else if (peek.right == pop) {
                    pop = stack.pop();
                }
                // 待处理右边
                else {
                    currt = peek.right;
                }
            }
        }

        return result;
    }





    /*
            1
           / \
          2   3
         /   / \
        4   5   6
     */
    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(new TreeNode(4), 2, null),
                1,
                new TreeNode(new TreeNode(5), 3, new TreeNode(6))
        );
        System.out.println(preorderTraversal(root));
    }

    /*
        31 红
        32 黄
        33 橙
        34 蓝
        35 紫
        36 绿
     */
    public static void colorPrintln(String origin, int color) {
        System.out.printf("\033[%dm%s\033[0m%n", color, origin);
    }



}
